import Toast from 'tdesign-miniprogram/toast/index';
import Dialog from 'tdesign-miniprogram/dialog/index';
import requestApi from "../../../../../utils/request"
import { OrderButtonTypes } from '../../config';

Component({
  options: {
    addGlobalClass: true,
  },
  properties: {
    order: {
      type: Object,
      observer(order) {
        // 判定有传goodsIndex ，则认为是商品button bar, 仅显示申请售后按钮
        if (this.properties?.goodsIndex !== null) {
          const goods = order.goodsList[Number(this.properties.goodsIndex)];
          this.setData({
            buttons: {
              left: [],
              right: (goods.buttons || []).filter((b) => b.type == OrderButtonTypes.APPLY_REFUND),
            },
          });
          return;
        }
        // 订单的button bar 不显示申请售后按钮
        const buttonsRight = (order.buttons || [])
          // .filter((b) => b.type !== OrderButtonTypes.APPLY_REFUND)
          .map((button) => {
            //邀请好友拼团按钮
            if (button.type === OrderButtonTypes.INVITE_GROUPON && order.groupInfoVo) {
              const {
                groupInfoVo: { groupId, promotionId, remainMember, groupPrice },
                goodsList,
              } = order;
              const goodsImg = goodsList[0] && goodsList[0].imgUrl;
              const goodsName = goodsList[0] && goodsList[0].name;
              return {
                ...button,
                openType: 'share',
                dataShare: {
                  goodsImg,
                  goodsName,
                  groupId,
                  promotionId,
                  remainMember,
                  groupPrice,
                  storeId: order.storeId,
                },
              };
            }
            return button;
          });
        // 删除订单按钮单独挪到左侧
        const deleteBtnIndex = buttonsRight.findIndex((b) => b.type === OrderButtonTypes.DELETE);
        let buttonsLeft = [];
        if (deleteBtnIndex > -1) {
          buttonsLeft = buttonsRight.splice(deleteBtnIndex, 1);
        }
        this.setData({
          buttons: {
            left: buttonsLeft,
            right: buttonsRight,
          },
        });
      },
    },
    goodsIndex: {
      type: Number,
      value: null,
    },
    isBtnMax: {
      type: Boolean,
      value: false,
    },
  },

  data: {
    order: {},
    buttons: {
      left: [],
      right: [],
    },
  },

  methods: {
    // 点击【订单操作】按钮，根据按钮类型分发
    onOrderBtnTap(e) {
      const { type } = e.currentTarget.dataset;
      switch (type) {
        case OrderButtonTypes.DELETE:
          this.onDelete(this.data.order);
          break;
        case OrderButtonTypes.DELIVERY:
          this.ondelivery(this.data.order);
          break;
        case OrderButtonTypes.CANCEL:
          this.onCancel(this.data.order);
          break;
        case OrderButtonTypes.CONFIRM:
          this.onConfirm(this.data.order);
          break;
        case OrderButtonTypes.PAY:
          this.onPay(this.data.order);
          break;
        case OrderButtonTypes.APPLY_REFUND:
          this.onApplyRefund(this.data.order);
          break;
        case OrderButtonTypes.VIEW_REFUND:
          this.onViewRefund(this.data.order);
          break;
        case OrderButtonTypes.COMMENT:
          this.onAddComment(this.data.order);
          break;
        case OrderButtonTypes.INVITE_GROUPON:
          //分享邀请好友拼团
          break;
        case OrderButtonTypes.REBUY:
          this.onBuyAgain(this.data.order);
      }
    },

    onCancel(e) {
      const params = {
        id: e.id,
      }
      Dialog.confirm({
        title: '确定取消订单？',
        content: '',
        confirmBtn: '取消订单',
        cancelBtn: '取消',
      })
        .then(() => {
          requestApi.post('shopro/order/cancel', params, true).then(res => {
            if (res.code === 1) {
              Toast({
                context: this,
                selector: '#t-toast',
                message: '订单已取消',
                icon: 'check-circle',
              });
              this.triggerEvent('restInit')
            }
          })
        })
        .catch(() => {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '你取消了确认收货',
            icon: 'check-circle',
          });
        });
    },

    onConfirm(e) {
      let orderItemID = []
      if (e.goodsList.length > 1) {
        e.goodsList.forEach(item => {
          orderItemID.push(item.id)
        })
      }
      const params = {
        id: e.id,
        order_item_id: e.goodsList.length > 1 ? orderItemID.join(',') : e.goodsList[0].id
      }
      Dialog.confirm({
        title: '确认是否已经收到货？',
        content: '',
        confirmBtn: '确认收货',
        cancelBtn: '取消',
      })
        .then(() => {
          requestApi.post('shopro/order/confirm', params, true).then(res => {
            Toast({
              context: this,
              selector: '#t-toast',
              message: '确认收货成功',
              icon: 'check-circle',
            });
            this.triggerEvent('restInit')
          })
        })
        .catch(() => {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '你取消了确认收货',
            icon: 'check-circle',
          });
        });
    },
    ondelivery(e) {
      const logisticsData = {
        order_id: e.id//订单ID
      };
      wx.navigateTo({
        url: `/service/shoppingMall/Order/delivery-detail/index?data=${JSON.stringify(logisticsData)}`,
      });
    },
    onPay(e) {
      const { orderNo } = e
      const payParams = {
        //订单编码
        order_sn: orderNo,
        payment: 'wechat',
        openid: '1111',
        platform: 'wxMiniProgram'
      }
      requestApi.post('shopro/pay/prepay', payParams, true).then(re => {
        wx.requestPayment({
          timeStamp: re.data.pay_data.timeStamp,
          nonceStr: re.data.pay_data.nonceStr,
          package: re.data.pay_data.package,
          signType: re.data.pay_data.signType,
          paySign: re.data.pay_data.paySign,
          success: (res) => {
            Toast({
              context: this,
              selector: '#t-toast',
              message: '支付成功',
              duration: 2000,
              icon: '',
            });
            wx.reLaunch({
              url: '/service/shoppingMall/Order/order-list/index?status=nosend'
            })
          },
          fail: (res) => {
            Toast({
              context: this,
              selector: '#t-toast',
              message: '支付失败',
              duration: 2000,
              icon: '',
            });
          }
        })

      })
    },

    onBuyAgain() {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '你点击了再次购买',
        icon: 'check-circle',
      });
    },

    onApplyRefund(order) {
      const goods = order.goodsList[this.properties.goodsIndex];
      const params = {
        orderNo: order.orderNo,
        skuId: order.id,
        // spuId: goods?.spuId ?? '28373847384343',
        orderStatus: order.status,
        logisticsNo: order.logisticsNo,
        price: order.totalAmount,
        num: order,
        createTime: order.createTime,
        orderAmt: order.totalAmount,
        payAmt: order.amount,
        canApplyReturn: true,
        orderId: order.goodsList[0].id
      };
      const paramsStr = Object.keys(params)
        .map((k) => `${k}=${params[k]}`)
        .join('&');
      wx.navigateTo({ url: `/service/shoppingMall/Order/apply-service/index?${paramsStr}` });
    },

    onViewRefund() {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '你点击了查看退款',
        icon: '',
      });
    },

    /** 添加订单评论 */
    onAddComment(order) {
      const orderItemId = []
      if (order.goodsList.length > 1) {
        order.goodsList.forEach(item => {
          orderItemId.push(item.id)
        })
      }

      console.log(orderItemId)
      const orderData = {
        imgUrl: order.goodsList[0].thumb,
        title: order.goodsList[0].title,
        id: order?.id,
        orderItemId: orderItemId.length > 0 ? orderItemId.join(',') : order.goodsList[0].id
      }
      wx.setStorageSync('order.orderItem', JSON.stringify(orderData));
      wx.navigateTo({
        url: `/service/shoppingMall/Goods/comments/create/index`,
      });
    },
  },
});
